package com.liuzh.kaoyanspringboot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liuzh.kaoyanspringboot.common.Constants;
import com.liuzh.kaoyanspringboot.entity.Article;
import com.liuzh.kaoyanspringboot.entity.Collect;
import com.liuzh.kaoyanspringboot.entity.CollectArticle;
import com.liuzh.kaoyanspringboot.mapper.CollectArticleMapper;
import com.liuzh.kaoyanspringboot.mapper.CollectMapper;
import com.liuzh.kaoyanspringboot.service.ArticleService;
import com.liuzh.kaoyanspringboot.service.CollectService;
import com.liuzh.kaoyanspringboot.service.MessageService;
import com.liuzh.kaoyanspringboot.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.beans.Transient;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 用户文章收藏关联表 服务实现类
 * </p>
 *
 * @author 刘志鸿
 * @since 2023-03-15
 */
@Service
public class CollectServiceImpl extends ServiceImpl<CollectMapper, Collect> implements CollectService {

    @Resource
    private CollectArticleMapper collectArticleMapper;

    @Resource
    private CollectMapper collectMapper;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private MessageService messageService;

    @Transient
    @Override
    public void setCollectArticles(Integer collectId, List<Integer> articleIds) {
        // 先删除所有的绑定关系
        collectArticleMapper.deleteByCollectId(collectId);
        //再添加 前端传递的 articleIds
        for (Integer articleId : articleIds) {
            CollectArticle collectArticle = new CollectArticle();
            collectArticle.setCollectId(collectId);
            collectArticle.setArticleId(articleId);
            collectArticleMapper.insert(collectArticle);
        }
    }

    /**
     *  根据文章id 删除用户所有收藏夹里的该文章
     * @param articleId
     * @return
     */
    private Boolean deleteCollectArticle(Integer articleId) {
        List<Integer> userAllCollectIds = collectMapper.selectUserCollectIdList(TokenUtils.getCurrentUser().getId());
        for (Integer collectId : userAllCollectIds) {
            collectArticleMapper.deleteByOthers(articleId, collectId);
        }
        return true;
    }

    public Boolean setByArticleAndCollectIds(Integer articleId, List<Integer> collectIds) {
        for (Integer cId : collectIds) {
            collectArticleMapper.insertByOthers(articleId, cId);
        }
        articleService.increaseCollect(articleId);
        return true;
    }


    @Transient
    @Override
    public String setArticleCollects(Integer articleId, List<Integer> collectIds) {
        Integer currentUserId = TokenUtils.getCurrentUser().getId();

        // 获取用户所有的收藏夹 !!! 收藏夹不可能为空
        List<Integer> userAllcollectIds = collectMapper.selectUserCollectIdList(currentUserId);
        boolean isCollect = isCollect(articleId);
        // 首先删除原由关系
        for (Integer collectId : userAllcollectIds) {
            collectArticleMapper.deleteByOthers(articleId, collectId);
        }
        if (collectIds.isEmpty()) {
            if (isCollect) {
                articleService.decrementCollect(articleId);
                return "取消收藏成功";
            }
            else {
                return "未收藏";
            }
        }
        // 再增加新的关系
        for (Integer cId : collectIds) {
            collectArticleMapper.insertByOthers(articleId, cId);
        }
        if (!isCollect) {
            articleService.increaseCollect(articleId);
        }
        Article article = articleService.findById(articleId);
        Integer num = article.getCollect();
        if (num == 10 || num == 1000 || num == 10000){
            messageService.createAndSave(currentUserId,article.getUserId(), Constants.TYPE_ARTICLE, articleId,"恭喜文章"+ article.getName() +"收藏数超"+article.getCollect());
        }
        return "更改成功";
    }

    @Override
    public List<Collect> listByUser() {
//        TokenUtils.getCurrentUser().getId();
        QueryWrapper<Collect> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",TokenUtils.getCurrentUser().getId());
        return list(queryWrapper);
    }

    /**
     * 查询文章在用户的那几个收藏夹下的收藏夹Id
     * @param articleId
     * @return
     */
    @Override
    public List<Integer> getAInCoList(Integer articleId) {
        Integer userId = TokenUtils.getCurrentUser().getId();
        // 查出用户的所有收藏夹
        List<Integer> collectIdList = collectMapper.selectUserCollectIdList(userId);
        List<Integer> res = new ArrayList<>();
        // 查询每一个文件夹下是否有该文章
        for (Integer cId : collectIdList) {
            Integer num = collectArticleMapper.selectByOthers(articleId, cId);
            if (num != 0) {
                res.add(cId); //有则加入返回队列
            }
        }
        return res;
    }

    @Override
    public boolean isCollect(Integer articleId) {
        // 获取用户所有的收藏夹 !!! 收藏夹不可能为空
        List<Integer> userAllcollectIds = collectMapper.selectUserCollectIdList(TokenUtils.getCurrentUser().getId());
        //
        int count = 0;
        for (Integer cId : userAllcollectIds) {
            if (collectArticleMapper.selectByOthers(articleId,cId) > 0) {
               return true;
            }
        }
        return false;
    }

    @Override
    public Page<Collect> findPage(Page<Collect> page, String collectName, String username) {
        return collectMapper.findPage(page, collectName, username);
    }

    @Override
    @Transient
    public boolean deleteByCollectId(Integer collectId) {
        // 第一步解除关系
        collectArticleMapper.deleteByCollectId(collectId);
        return removeById(collectId);
    }

    @Override
    public Page<Article> getArticlesDetailByCollectId(Integer pageNum, Integer pageSize, Integer collectId, String articleName) {
        Page<Article> page = articleService.findCollectPage(new Page<>(pageNum, pageSize), collectId, articleName);
        return page;
    }


    @Override
    public int setCollectArticle(CollectArticle collectArticle) {
        return collectArticleMapper.insert(collectArticle);
    }


    @Override
    public List<Integer> getCollectArticle(Integer collectId) {
        return collectArticleMapper.selectByCollectId(collectId);
    }


    /**
     * 查询收藏夹文章内容
     * @param userId
     * @param collectName
     * @return
     */
    @Override
    public Collect getCollect(Integer userId, String collectName) {
        Collect collect = collectMapper.selectByNameAndUid(collectName,userId);
        if (collect == null) {
            return collect;
        }
        System.out.println(collect);
        Integer collectId = collect.getId();
        // 根据收藏夹id，从收藏文章关系表中，查出收藏夹里所对应的文章id
        List<Integer> articleIds = collectArticleMapper.selectByCollectId(collectId);
        List<Article> articles = new ArrayList<>();
        for (Integer articleId : articleIds)  {
            articles.add(articleService.miniFindById(articleId));
        }
        collect.setArticleList(articles);
        return collect;
    }


}
